extends Node2D
# -------------------------变量命名-----------------------#
@onready var weapon=$Sprite2D
@onready var shootPos=$ShotPos
@onready var timer=$Timer
@onready var bullet=preload('res://场景/物品/弹药/子弹.tscn')

const levelColor:=[
	'#b0c3d9',
	"#4b69ff",
	"#d32ce6",
	"#8847ff",
	"#eb4b4b",
]
var SHOOT_TIME=0.5
var BULLET_SPEED=20
var BULLET_HURT=1

# 装备者
var player:Player
# 锁敌集合
var enemies:=[]
# 武器等级
var level:=0
# 升级所需经验
var levelExp=8
var curExp=0

# -------------------------生命周期-----------------------#
# 初始化
func _ready() -> void:
	updateMat()
	player=get_parent().get_parent()

# 帧动画调用
func _physics_process(_delta:float)-> void:
	levelUp()
	if enemies.size()!=0:
		look_at(enemies[0].position)
	else:
		rotation_degrees=0
	pass

# 攻击范围检测到敌人
func _on_area_2d_body_entered(body:Node2D) -> void:
	if body.is_in_group('enemy') and !enemies.has(body):
		enemies.append(body)
	sort_enemy()
		
# 敌人脱离攻击范围
func _on_area_2d_body_exited(body:Node2D) -> void:
	if body.is_in_group('enemy') and enemies.has(body):
		enemies.erase(body)

# 武器间隔时间调用
func _on_timer_timeout() -> void:
	if enemies.size()!=0:
		shot(enemies[0].position)

# -------------------------响应函数-----------------------#
# 射击
func shot(pos):
	var curBullet =bullet.instantiate()
	curBullet.speed=BULLET_SPEED
	curBullet.hurt=(BULLET_HURT+player.stats.damage)*player.stats.damageRate
	# 射击位置本身是局部坐标
	curBullet.position=shootPos.global_position
	var dir=(pos-curBullet.position).normalized()
	curBullet.dir=dir
	curBullet.target=pos
	get_tree().root.add_child(curBullet)
	curExp+=1
	pass

# 设置材质
func updateMat():
	weapon.material.set_shader_parameter('color',Color(levelColor[level]))

# 按敌人的远近排序
func sort_enemy():
	if enemies.size()!=0:
		enemies.sort_custom(
			func(a,b):
				return a.position.distance_to(player.position)<b.position.distance_to(player.position)
		)

# 武器升级
func levelUp():
	if curExp>=levelExp:
		curExp-=levelExp
		levelExp*=2
		level+=1
		SHOOT_TIME-=SHOOT_TIME/10
		BULLET_SPEED+=2
		BULLET_HURT+=1
		updateMat()


